package com.ophiux.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ophiux.common.core.base.Result;
import com.ophiux.common.core.enums.ResultEnum;
import com.ophiux.member.mapper.MemberMailAddressMapper;
import com.ophiux.member.model.dto.MemberMailAddressDTO;
import com.ophiux.member.model.entity.MemberMailAddress;
import com.ophiux.member.model.vo.MemberMailAddressAddVo;
import com.ophiux.member.model.vo.MemberMailAddressQueryVo;
import com.ophiux.member.model.vo.MemberMainAddressUpdateVo;
import com.ophiux.member.service.IMemberMailAddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MemberMailAddressServiceImpl extends ServiceImpl<MemberMailAddressMapper, MemberMailAddress> implements IMemberMailAddressService {
	@Autowired
	MemberMailAddressMapper memberMailAddressMapper;

	@Override
	public IPage<MemberMailAddressDTO> getPage(IPage<MemberMailAddress> iPage, MemberMailAddressQueryVo queryDTO) {
		LambdaQueryWrapper<MemberMailAddress> lambda = new LambdaQueryWrapper<MemberMailAddress>();
		lambda.eq(!ObjectUtils.isEmpty(queryDTO.getMemberId()),MemberMailAddress::getMemberId,queryDTO.getMemberId());
		
		IPage<MemberMailAddress> page = this.page(iPage, lambda);
		return page.convert(x->{
			MemberMailAddressDTO dto = new MemberMailAddressDTO();
			BeanUtils.copyProperties(x,dto);
			return dto;
		});
	}

	@Override
	public Result insert(MemberMailAddressAddVo vo) {
		int addressCount = memberMailAddressMapper.getAddressCountByMemberId(vo.getMemberId());
		if(addressCount == 3) {
			return Result.fail("邮寄地址已达上限");
		}
		
		MemberMailAddress data = new MemberMailAddress();
		BeanUtils.copyProperties(vo,data);
		int effCount = this.baseMapper.insert(data);
		if(effCount>0) return Result.success();
		return Result.fail();
	}

	@Override
	public Result update(MemberMainAddressUpdateVo vo) {
		MemberMailAddress data = this.getById(vo.getId());
		if(data == null) return Result.fail(ResultEnum.DATA_NOT_FOUND);
		
		BeanUtils.copyProperties(vo,data);

		boolean isSuccess = this.updateById(data);
		if(!isSuccess) return Result.fail(ResultEnum.DATA_UPDATE_FAIL);
		
		return Result.success(ResultEnum.requestSuccess);
	}
	
	
	@Override
	public Result delete(String ids) {
		List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
		boolean effCount = removeByIds(list);
		if(effCount) return Result.success();
		return Result.fail();
	}

}
